<template>
  <div class="device-map-container">
    <div class="map-header">
      <div class="map-title">
        <el-icon :size="24" color="#409EFF"><Location /></el-icon>
        <h3>设备分布地图</h3>
      </div>
      <div class="map-controls">
        <el-tooltip content="刷新设备位置" placement="top">
          <el-button type="primary" circle @click="refreshMap">
            <el-icon><Refresh /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="筛选设备" placement="top">
          <el-button type="primary" circle @click="showFilterDialog = true">
            <el-icon><Filter /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <!-- 地图容器 -->
    <div id="map-container" ref="mapContainerRef">
      <div id="map" ref="mapElement"></div>
    </div>

    <!-- 图例 -->
    <div class="map-legend">
      <div class="legend-item">
        <div class="legend-icon online"></div>
        <span>在线设备</span>
      </div>
      <div class="legend-item">
        <div class="legend-icon offline"></div>
        <span>离线设备</span>
      </div>
      <div class="legend-item">
        <div class="legend-icon warning"></div>
        <span>警告设备</span>
      </div>
    </div>

    <!-- 设备筛选对话框 -->
    <el-dialog
      title="设备筛选"
      v-model="showFilterDialog"
      width="400px"
    >
      <el-form label-width="80px">
        <el-form-item label="设备状态">
          <el-select v-model="filter.status" multiple placeholder="请选择状态">
            <el-option label="在线" value="online"></el-option>
            <el-option label="离线" value="offline"></el-option>
            <el-option label="警告" value="warning"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select v-model="filter.type" multiple placeholder="请选择类型">
            <el-option label="传感器" value="sensor"></el-option>
            <el-option label="控制器" value="controller"></el-option>
            <el-option label="执行器" value="actuator"></el-option>
            <el-option label="网关" value="gateway"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showFilterDialog = false">取消</el-button>
        <el-button type="primary" @click="applyFilter">应用筛选</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, shallowRef, nextTick } from 'vue';
import { Location, Refresh, Filter } from '@element-plus/icons-vue';
import { MapLoader } from '@/utils/map'; // 导入地图加载器

// 定义AMap类型接口（解决类型未知问题）
interface AMapType {
  Map: new (container: string | HTMLElement, options?: any) => AMapMap;
  Marker: new (options?: any) => AMapMarker;
  Icon: new (options?: any) => any;
  Pixel: new (x: number, y: number) => any;
  Bounds: new (southWest: any, northEast: any) => any;
  Zoom: new (options?: any) => any;
}

interface AMapMap {
  add: (layer: any) => void;
  remove: (layer: any) => void;
  setCenter: (center: [number, number]) => void;
  setZoom: (zoom: number) => void;
  setBounds: (bounds: any, immediately?: boolean, avoid?: number[]) => void;
  destroy: () => void;
  addControl: (control: any) => void;
  resize: () => void;
  on: (event: string, callback: () => void) => void;
}

interface AMapMarker {
  on: (event: string, callback: () => void) => void;
}

interface Device {
  id: number;
  name: string;
  type: string;
  status: 'online' | 'offline' | 'warning';
  position: [number, number];
}

// 使用 shallowRef 优化地图实例性能
const mapInstance = shallowRef<AMapMap | null>(null);
const markers = shallowRef<any[]>([]); // 使用any避免复杂类型问题
const showFilterDialog = ref(false);
const mapElement = ref<HTMLElement | null>(null);
const mapContainerRef = ref<HTMLElement | null>(null); // 地图容器引用

// 设备筛选条件
const filter = ref({
  status: ['online', 'warning', 'offline'] as Device['status'][],
  type: ['sensor', 'controller', 'actuator', 'gateway']
});

// 设备数据
const devices = ref<Device[]>([
  { id: 1, name: '温度传感器#01', type: 'sensor', status: 'online', position: [108.953098, 34.277800] },
  { id: 2, name: '压力控制器#02', type: 'controller', status: 'warning', position: [108.966, 34.262] },
  { id: 3, name: '流量计#03', type: 'sensor', status: 'offline', position: [108.94, 34.272] },
  { id: 4, name: '阀门执行器#04', type: 'actuator', status: 'online', position: [108.95, 34.265] },
  { id: 5, name: '网关设备#05', type: 'gateway', status: 'online', position: [108.96, 34.275] },
  { id: 6, name: '液位传感器#06', type: 'sensor', status: 'online', position: [108.945, 34.268] },
  { id: 7, name: '控制面板#07', type: 'controller', status: 'warning', position: [108.958, 34.282] },
  { id: 8, name: '泵控制器#08', type: 'controller', status: 'offline', position: [108.975, 34.258] },
]);

// 确保地图容器有正确高度
const ensureMapContainerHeight = () => {
  if (mapContainerRef.value) {
    const parent = mapContainerRef.value.parentElement;
    if (parent) {
      const top = parent.getBoundingClientRect().top;
      const height = Math.max(window.innerHeight - top - 50, 400);
      mapContainerRef.value.style.height = `${height}px`;
      
      // 地图实例存在时调整大小
      if (mapInstance.value) {
        nextTick(() => {
          mapInstance.value?.resize();
        });
      }
    }
  }
};

// 初始化地图
const initMap = async () => {
  try {
    const AMap = (await MapLoader()) as unknown as AMapType;
    
    if (!mapElement.value) return;
    
    // 确保高度正确
    ensureMapContainerHeight();
    
    mapInstance.value = new AMap.Map(mapElement.value, {
      zoom: 13,
      center: [108.953098, 34.277800],
      viewMode: '3D',
      mapStyle: 'amap://styles/normal' // 使用正常样式解决黑色背景
    });
    
    // 添加缩放控件
    mapInstance.value.addControl(new AMap.Zoom());
    
    // 初始渲染设备
    renderDevices(AMap);
    
  } catch (error) {
    console.error('地图初始化失败:', error);
  }
};

// 设备状态颜色映射
const statusColors: Record<Device['status'], string> = {
  online: '#67c23a',
  offline: '#909399',
  warning: '#e6a23c'
};

// 创建标记
const createMarker = (device: Device, AMap: AMapType) => {
  return new AMap.Marker({
    position: device.position,
    content: `
      <div style="
        width: 16px;
        height: 16px;
        border-radius: 50%;
        background: ${statusColors[device.status]};
        border: 2px solid white;
        box-shadow: 0 2px 4px rgba(0,0,0,0.3);
        cursor: pointer;
      "></div>
    `,
    offset: new AMap.Pixel(-8, -8)
  });
};

// 渲染设备标记
const renderDevices = (AMap: AMapType) => {
  if (!mapInstance.value) return;
  
  // 清除现有标记
  clearMarkers();
  
  const filteredDevices = devices.value.filter(device => 
    filter.value.status.includes(device.status) &&
    filter.value.type.includes(device.type)
  );
  
  // 创建新标记
  const newMarkers = filteredDevices.map(device => {
    const marker = createMarker(device, AMap);
    
    marker.on('click', () => {
      console.log(`点击设备: ${device.name}`);
      // 设备详情逻辑...
    });
    
    mapInstance.value!.add(marker);
    return marker;
  });
  
  markers.value = newMarkers;
  
  // 设置地图视图
  if (filteredDevices.length > 0) {
    try {
      const bounds = new AMap.Bounds(0,0);
      filteredDevices.forEach(d => bounds.extend(d.position));
      mapInstance.value.setBounds(bounds, true, [50, 50, 50, 50]); // 添加边距
    } catch (error) {
      console.error('设置地图边界失败:', error);
      // 回退到默认视图
      mapInstance.value.setCenter([108.953098, 34.277800]);
      mapInstance.value.setZoom(13);
    }
  } else {
    mapInstance.value.setCenter([108.953098, 34.277800]);
    mapInstance.value.setZoom(13);
  }
};

// 清除所有标记
const clearMarkers = () => {
  if (mapInstance.value) {
    markers.value.forEach(marker => {
      try {
        mapInstance.value?.remove(marker);
      } catch (e) {
        console.warn('移除标记失败:', e);
      }
    });
  }
  markers.value = [];
};

// 刷新地图
const refreshMap = async () => {
  console.log("刷新设备位置");
  try {
    const AMap = (await MapLoader()) as unknown as AMapType;
    renderDevices(AMap);
  } catch (error) {
    console.error('刷新地图失败:', error);
  }
};

// 应用筛选
const applyFilter = async () => {
  try {
    const AMap = (await MapLoader()) as unknown as AMapType;
    renderDevices(AMap);
    showFilterDialog.value = false;
  } catch (error) {
    console.error('应用筛选失败:', error);
  }
};

onMounted(() => {
  initMap();
  // 监听窗口变化调整地图高度
  window.addEventListener('resize', ensureMapContainerHeight);
});

onUnmounted(() => {
  if (mapInstance.value) {
    try {
      mapInstance.value.destroy();
    } catch (e) {
      console.warn('销毁地图实例失败:', e);
    }
    mapInstance.value = null;
  }
  window.removeEventListener('resize', ensureMapContainerHeight);
});
</script>

<style scoped>
.device-map-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
}

.map-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.map-title h3 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.map-controls {
  display: flex;
  gap: 8px;
}

#map-container {
  flex: 1;
  position: relative;
  min-height: 400px;
}

#map {
  width: 100%;
  height: 100%;
}

.map-legend {
  position: absolute;
  bottom: 15px;
  right: 15px;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px 14px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 15px;
  z-index: 100;
  font-size: 13px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.legend-icon {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.legend-icon.online {
  background-color: #67c23a;
}

.legend-icon.offline {
  background-color: #909399;
}

.legend-icon.warning {
  background-color: #e6a23c;
}
</style>